﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace CSharpServer
{
	public class RemoteClient
	{
		private TcpClient client;
		private NetworkStream stream;
		private const int BufferSize = 10240;
		private byte[] buffer;
		private RequestHandler handler;

		public RemoteClient(TcpClient client)
		{
			this.client = client;

			Console.WriteLine("\nClient Connected! {0} <-- {1}",
								client.Client.LocalEndPoint,
								client.Client.RemoteEndPoint);

			stream = client.GetStream();
			buffer = new byte[BufferSize];

			handler = new RequestHandler();

			AsyncCallback callBack = new AsyncCallback(ReadComplete);//ReadComplete;
			stream.BeginRead(buffer, 0, BufferSize, callBack, null);
		}

		private void ReadComplete(IAsyncResult ar)
		{
			int bytesRead = 0;
			try
			{
				lock (stream)
				{
					bytesRead = stream.EndRead(ar);
					Console.WriteLine("Reading data, {0} bytes ...", bytesRead);
				}

				if (bytesRead == 0)
				{
					throw new Exception("读到0字节");
				}

				string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
				Array.Clear(buffer, 0, buffer.Length);

				string[] msgArray = handler.GetActualString(msg);

				foreach (string m in msgArray)
				{
					Console.WriteLine("Received: {0}", m);

					string back = m.ToUpper();
					byte[] temp = Encoding.Unicode.GetBytes(back);
					stream.Write(temp, 0, temp.Length);
					stream.Flush();
					Console.WriteLine("Sent: {0}", back);
				}

				lock (stream)
				{
					AsyncCallback callBack = new AsyncCallback(ReadComplete);
					stream.BeginRead(buffer, 0, BufferSize, callBack, null);
				}
			}
			catch (System.Exception ex)
			{
				if (stream != null)
				{
					stream.Dispose();
				}
				client.Close();
				Console.WriteLine(ex.Message);
			}
		}
	}
}
